/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormPiutang.java
 *
 * Created on Feb 2, 2011, 4:46:58 PM
 */

package juwita;

import config.DBConnection;
import java.awt.Color;
import java.sql.*;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumn;


/**
 *
 * @author Abah
 */
public class FormPiutang extends javax.swing.JInternalFrame {

    private DefaultTableModel DftTabMode;
    java.sql.Connection conn = new DBConnection().connect();
    String sTglDibayar = "";
    
    /** Creates new form FormPiutang */
    public FormPiutang() {
        initComponents();
        btnEdit.setEnabled(false);       
        tbPiutang.getTableHeader().setReorderingAllowed(false);
        Object[] Baris={"Kd Jual","Nama","Tanggal","Piutang"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbPiutang.setModel(DftTabMode);

        tampilData();
        kosongkan();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnTengah = new javax.swing.JPanel();
        spPiutang = new javax.swing.JScrollPane();
        tbPiutang = new javax.swing.JTable();
        pnAtas = new javax.swing.JPanel();
        btnEdit = new javax.swing.JButton();
        txtNamaPlg = new javax.swing.JTextField();
        txtKdJual = new javax.swing.JTextField();
        lbStatus = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        btnShowAll = new javax.swing.JButton();
        txtSearch = new javax.swing.JTextField();
        cbSearch = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        txtDibayar = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        dcTglDibayar = new com.toedter.calendar.JDateChooser();
        txtTotalPiutang = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Data Piutang");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/piutang.png"))); // NOI18N
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        pnTengah.setBackground(new java.awt.Color(255, 255, 255));
        pnTengah.setLayout(new java.awt.BorderLayout());

        tbPiutang.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tbPiutang.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tbPiutangMousePressed(evt);
            }
        });
        tbPiutang.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbPiutangKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbPiutangKeyReleased(evt);
            }
        });
        spPiutang.setViewportView(tbPiutang);

        pnTengah.add(spPiutang, java.awt.BorderLayout.CENTER);

        pnAtas.setBackground(new java.awt.Color(255, 255, 255));
        pnAtas.setPreferredSize(new java.awt.Dimension(410, 275));
        pnAtas.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnEdit.setText("Edit");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        pnAtas.add(btnEdit, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 190, 70, -1));

        txtNamaPlg.setEditable(false);
        txtNamaPlg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNamaPlgKeyReleased(evt);
            }
        });
        pnAtas.add(txtNamaPlg, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 70, 240, -1));

        txtKdJual.setEditable(false);
        txtKdJual.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtKdJualKeyReleased(evt);
            }
        });
        pnAtas.add(txtKdJual, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 50, 160, -1));

        lbStatus.setFont(new java.awt.Font("Tahoma", 1, 18));
        lbStatus.setForeground(new java.awt.Color(255, 0, 0));
        lbStatus.setText("BELUM LUNAS");
        pnAtas.add(lbStatus, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 192, -1, 30));

        jLabel4.setText("Status");
        pnAtas.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 200, -1, -1));

        btnShowAll.setText("Show All");
        btnShowAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnShowAllActionPerformed(evt);
            }
        });
        pnAtas.add(btnShowAll, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 250, 80, -1));
        pnAtas.add(txtSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 250, 190, -1));

        cbSearch.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kd Jual", "Nama", "Tanggal" }));
        pnAtas.add(cbSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 230, 100, -1));

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });
        pnAtas.add(btnSearch, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 250, 70, -1));

        txtDibayar.setFont(new java.awt.Font("Tahoma", 1, 11));
        txtDibayar.setForeground(new java.awt.Color(0, 153, 51));
        txtDibayar.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtDibayar.setText("0");
        pnAtas.add(txtDibayar, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 120, 210, -1));

        jLabel6.setText("Piutang Dibayar");
        pnAtas.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 120, -1, -1));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/p_piutang.png"))); // NOI18N
        pnAtas.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 90, 120, 100));

        jLabel5.setText("Tanggal");
        pnAtas.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, -1, -1));

        dcTglDibayar.setDateFormatString("dd/MM/yyyy");
        dcTglDibayar.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                dcTglDibayarPropertyChange(evt);
            }
        });
        pnAtas.add(dcTglDibayar, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 90, 140, -1));

        txtTotalPiutang.setFont(new java.awt.Font("Tahoma", 1, 18));
        txtTotalPiutang.setForeground(new java.awt.Color(0, 153, 0));
        txtTotalPiutang.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTotalPiutang.setText("0");
        txtTotalPiutang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTotalPiutangActionPerformed(evt);
            }
        });
        pnAtas.add(txtTotalPiutang, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 150, 210, 30));

        jLabel7.setText("Nama");
        pnAtas.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 70, -1, -1));

        jLabel8.setText("Kode Jual");
        pnAtas.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, -1, -1));

        jLabel9.setText("Total Piutang");
        pnAtas.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 150, -1, -1));

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel10.setForeground(new java.awt.Color(0, 153, 51));
        jLabel10.setText("P I U T A N G");
        pnAtas.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, -1, -1));

        pnTengah.add(pnAtas, java.awt.BorderLayout.PAGE_START);

        getContentPane().add(pnTengah, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        // TODO add your handling code here:
        int clossing;
        clossing = JOptionPane.showConfirmDialog(this,
                "Tutup Data Piutang?",
                "Konfirmasi",
                JOptionPane.YES_NO_OPTION);
        if (clossing == 0){
            this.dispose();
            FormMain.isfPiu = false;
        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void tbPiutangMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPiutangMousePressed
        getDataFromTable();
}//GEN-LAST:event_tbPiutangMousePressed

    private void tbPiutangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbPiutangKeyPressed
        // TODO add your handling code here:
}//GEN-LAST:event_tbPiutangKeyPressed

    private void tbPiutangKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbPiutangKeyReleased
        // TODO add your handling code here:
        getDataFromTable();
}//GEN-LAST:event_tbPiutangKeyReleased

    private void txtNamaPlgKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNamaPlgKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNamaPlgKeyReleased

    private void txtKdJualKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKdJualKeyReleased
        // TODO add your handling code here:
}//GEN-LAST:event_txtKdJualKeyReleased

    private void btnShowAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnShowAllActionPerformed
        // TODO add your handling code here:
        tampilData();
        txtSearch.setText("");
}//GEN-LAST:event_btnShowAllActionPerformed

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        // TODO add your handling code here:
        tampilTabelSearch();
        kosongkan();
}//GEN-LAST:event_btnSearchActionPerformed

    private void dcTglDibayarPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_dcTglDibayarPropertyChange
        // TODO add your handling code here:
        if(dcTglDibayar.getDate()!=null){
            //format yyyy-MM-dd utk mysql
            SimpleDateFormat formatTgl = new SimpleDateFormat("yyyy-MM-dd");
            sTglDibayar= formatTgl.format(dcTglDibayar.getDate());
        }
}//GEN-LAST:event_dcTglDibayarPropertyChange

    private void txtTotalPiutangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTotalPiutangActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_txtTotalPiutangActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        // TODO add your handling code here:        
        editData();
}//GEN-LAST:event_btnEditActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnShowAll;
    private javax.swing.JComboBox cbSearch;
    private com.toedter.calendar.JDateChooser dcTglDibayar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel lbStatus;
    private javax.swing.JPanel pnAtas;
    private javax.swing.JPanel pnTengah;
    private javax.swing.JScrollPane spPiutang;
    private javax.swing.JTable tbPiutang;
    private javax.swing.JTextField txtDibayar;
    private javax.swing.JTextField txtKdJual;
    private javax.swing.JTextField txtNamaPlg;
    private javax.swing.JTextField txtSearch;
    private javax.swing.JTextField txtTotalPiutang;
    // End of variables declaration//GEN-END:variables

    private void kosongkan(){
        txtKdJual.setText("");        
        txtNamaPlg.setText("");        
        txtDibayar.setText("");
        lbStatus.setText("-");
        lbStatus.setForeground(Color.BLACK);
        btnEdit.setEnabled(false);
    }
    
    private void tampilData(){
        Object[] Baris={"Kd Jual","Nama","Tanggal","Piutang"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbPiutang.setModel(DftTabMode);
        int widths[] = {50, 100, 100, 250};
        for(int i=0;i<tbPiutang.getColumnCount();i++){
            TableColumn column = tbPiutang.getColumnModel().getColumn(i);
            column.setPreferredWidth(widths[i]);
        }
                
        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select a.*, b.n from tpiutang " +
                    "WHERE ");
            while (rslt.next()) {
                String sIdJual = rslt.getString("idJual");
                String sNamaPlg = rslt.getString("nmPeg");

                String[] dataField = {sIdJual, sIdJual};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }

    private void tampilTabelSearch(){

        String srcby = "";
        if(cbSearch.getSelectedItem().toString().equals("Username")){
            srcby = "user_id";
        }else{
            srcby = "nmPeg";
        }

        Object[] Baris={"Kode","Nama"};
        DftTabMode=new DefaultTableModel(null,Baris);
        tbPiutang.setModel(DftTabMode);

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery(
                    "SELECT * FROM tpeg WHERE UPPER(" + srcby +
                    ") like UPPER('%" +
                    txtSearch.getText() + "%')");

            while (rslt.next()) {
                String sUserId = rslt.getString("user_id");
                String sNamaPeg = rslt.getString("nmPeg");

                String[] dataField = {sUserId, sNamaPeg};
                DftTabMode.addRow(dataField);
            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
    }
    private void deleteData(){
            try {
                int deleting;
                deleting = JOptionPane.showConfirmDialog(this,
                        "Apakah Anda yakin akan menghapus "

                        //+ cbKodeKota.getSelectedItem().toString() +" "
                        +txtNamaPlg.getText() +"?",
                        "Konfirmasi",
                        JOptionPane.YES_NO_OPTION);
                if (deleting == 0){

                    PreparedStatement pStatement = null;
                    String sql = "DELETE FROM tpeg " +
                            "WHERE user_id=? ";
                    pStatement = conn.prepareStatement(sql);

                    pStatement.setString(1, txtKdJual.getText());

                    int intTambah = pStatement.executeUpdate();
                    if (intTambah >0){
                        JOptionPane.showMessageDialog(this,
                                "Delete sukses", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);

                    }else {
                        JOptionPane.showMessageDialog(this,
                                "Delete gagal", "Informasi",
                                JOptionPane.INFORMATION_MESSAGE);
                    }

                    pStatement.close();

                    kosongkan();
                    tampilData();
                }
            } catch(SQLException e){
                System.out.println("koneksi gagal " + e.toString());
            }
    }
    private boolean isDuplicatePKey(){
        String pKey = txtKdJual.getText();
        boolean result = true;
        int row = 0;

        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tpeg WHERE user_id=" +
                    "'" +pKey+ "'");
            while (rslt.next()) {
                row = rslt.getRow();
            }
                if(row > 0){
                    JOptionPane.showMessageDialog(this, "Kode "+pKey+" sudah ada"
                            ,"Peringatan",JOptionPane.WARNING_MESSAGE);
                    result = true;
                }else{
                    result = false;
                }
            System.out.println("row : " + row);
        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }
        return result;
    }
    private void insertData(){       
        
        java.sql.PreparedStatement pStatement = null;
        String sql = "INSERT INTO tpeg " +
                "(user_id, nmPeg, jk, alamat, tlp, hp, tgl_insert, tgl_update,status, password) " +
                "VALUES (?,?,?,?,?,?,now(),now(),?,?)";
        try {
            pStatement = conn.prepareStatement(sql);
            pStatement.setString(1, txtKdJual.getText());
            pStatement.setString(2, txtNamaPlg.getText());
            pStatement.setString(5, txtDibayar.getText());           


            int intTambah = pStatement.executeUpdate();
            if (intTambah>0){
                JOptionPane.showMessageDialog(this,
                        "Penambahan sukses", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this,
                        "Penambahan gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }
            pStatement.close();
            //conn.close();

            kosongkan();
            tampilData();

        }
        catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }

    }

     private void editData(){

        try {
            PreparedStatement pStatement = null;
            String sql = "UPDATE tPeg " +
                    "SET nmPeg=?, jk=?, alamat=?, tlp=?, hp=?, status=?, password=?, tgl_update=now() " +
                    "WHERE user_id=? ";
            pStatement = conn.prepareStatement(sql);

            pStatement.setString(1, txtNamaPlg.getText());            
            pStatement.setString(4, txtDibayar.getText());
            pStatement.setString(8, txtKdJual.getText());

            int intTambah = pStatement.executeUpdate();
            if (intTambah >0){
                JOptionPane.showMessageDialog(this,
                        "Data telah diupdate!", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);

            }else {
                JOptionPane.showMessageDialog(this,
                        "Edit gagal", "Informasi",
                        JOptionPane.INFORMATION_MESSAGE);
            }

            pStatement.close();
            kosongkan();
            tampilData();


        } catch(SQLException e){
            System.out.println("koneksi gagal " + e.toString());
        }
    }
    private void getDataFromTable(){
                // TODO add your handling code here:
        Object oUserId, oNamaPeg, oJk;

        oUserId = tbPiutang.getValueAt(tbPiutang.getSelectedRow(), 0);
        oNamaPeg = tbPiutang.getValueAt(tbPiutang.getSelectedRow(), 1);


        try {
            java.sql.Statement stmt = conn.createStatement();
            java.sql.ResultSet rslt = stmt.executeQuery("Select * from tpeg WHERE user_id=" +
                    "'" +oUserId+ "'");
            while (rslt.next()) {
                txtDibayar.setText(rslt.getString("tlp"));

            }

        }
        catch(SQLException e) {
            System.out.println("gagal : " + e.toString());
        }

        /*
        if(oTest == null){
            oTest = " ";
        }
         *
         */

        txtKdJual.setText(oUserId.toString());
        txtNamaPlg.setText(oNamaPeg.toString());

        btnEdit.setEnabled(true);
    }    
}
